package gold.github.CloudCenter.interceptor;

import gold.github.CloudCenter.annotation.Authorize;
import gold.github.CloudCenter.model.User;
import gold.github.CloudCenter.sevice.IUserService;
import gold.github.CloudCenter.utils.JwtUtil;
import gold.github.CloudCenter.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author: XYBH
 * @Description:
 * @Date: Created in 2020/4/27 0027 0:19
 * @Modified:
 */
@Service
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        //如果有注解Authorize，就需要验证token
        if (method.isAnnotationPresent(Authorize.class)) {
            Authorize userLoginToken = method.getAnnotation(Authorize.class);
            if (userLoginToken.required()) {
                // 从 http 请求头中取出 token
                String token = request.getHeader("authorization");
                log.info(token);
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取token中的userId
                String userId;
                try {
                    // 验证密码
                    boolean verify = JwtUtil.verify(token);
                    if (!verify) {
                        throw new RuntimeException("401");
                    }
                    // 获取userId
                    userId = JwtUtil.getClaim(token).get("id", String.class);
                    String authString = redisUtil.get(userId, 0);
                    int auth;
                    if (StringUtils.isEmpty(authString)) {
                        User user = userService.getUserByUserId(userId);
                        auth = user.getAuth();
                        //TODO:用户不存在
                    }
                    auth = Integer.parseInt(authString);
                    if (auth == 0) {
                        throw new RuntimeException("403权限不足");
                    }
                    // 添加request参数，用于传递userId
                    request.setAttribute("userId", userId);
                    // 根据userId 查询用户信息
                    User user = userService.getUserByUserId(userId);
                    if (user == null) {
                        throw new RuntimeException("用户不存在，请重新登录");
                    }
                    String sessionKey = JwtUtil.getClaim(token).get("sessionKey", String.class);
                    // 添加request参数，用于传递sessionKey
                    request.setAttribute("sessionKey", sessionKey);
                    System.out.println("获取到的数据为:"+userId+" "+sessionKey);
                    return true;
                } catch (RuntimeException e) {
                    e.getMessage();
                }
            }
            return true;
        }
        return true;
    }
}
